package com.hzit.mmcb.core.controller.admin;


import com.alibaba.excel.EasyExcel;
import com.hzit.common.result.R;
import com.hzit.mmcb.core.pojo.dto.ExcelDict;
import com.hzit.mmcb.core.pojo.entity.Dict;
import com.hzit.mmcb.core.service.DictService;
import com.hzit.mmcb.core.service.FileService;
import com.sun.deploy.net.URLEncoder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * <p>
 * 数据字典 前端控制器
 * </p>
 *
 * @author ljh
 * @since 2024-08-27
 */
@RestController
@RequestMapping("/admin/core/dict")
@Api(tags = "字典上传与下载")
public class AdminDictController {
    @Autowired
    private DictService dictService;

    @PostMapping("/import")
    @ApiOperation("上传")
    public R upload(@RequestBody @ApiParam("需要上传的文件") MultipartFile file) throws IOException {
        InputStream inputStream = file.getInputStream();
        dictService.upload(inputStream);
        return R.ok().message("上传成功");
    }

    @GetMapping("export")
    @ApiOperation("下载字典文件")
    public void export(HttpServletResponse response) throws IOException {
        // 这里注意 使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        //文件名
        String fileName= URLEncoder.encode("毛毛虫宝数据字典", "UTF-8").replaceAll("\\+", "%20");
        //传出数据
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), ExcelDict.class).sheet("数据字典").doWrite(dictService.listExcelDictDTO());
        // return R.ok().message("下载成功");

    }

    @GetMapping("/findByPid/{pid}")
    @ApiOperation("根据父节点id寻找字节")
    public R findByPid(@PathVariable @ApiParam(value = "父id",required = true) Integer pid){
        List<Dict> list= dictService.findById(pid);
        return R.ok().data("list",list);
    }
}

